package juc.aqs.customelock;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * 基于 AQS 实现 公平,不可重入锁
 *
 * @author hck
 */
public class CustomLock {
    private Sync sync;

    public CustomLock() {
        sync = new Sync();
    }

    public void lock() {
        sync.acquire(1);
    }

    public void unlock() {
        sync.release(0);
    }


    private static final class Sync extends AbstractQueuedSynchronizer {
        @Override
        protected boolean tryAcquire(int arg) {
            int state = getState();
            if (state == 0) {
                if (compareAndSetState(0, arg)) {
                    setExclusiveOwnerThread(Thread.currentThread());
                    return true;
                }
                return false;
            }
            return false;
        }

        @Override
        protected boolean tryRelease(int arg) {
            Thread t = Thread.currentThread();
            if (t != getExclusiveOwnerThread()) {
                throw new IllegalMonitorStateException();
            }
            return compareAndSetState(1, 0);
        }
    }
}
